import { ref } from 'vue'
import { designWidth as baseWidth, designHeight as baseHeight } from '@/constant/index'

export default function useDraw() {
  // * 指向最外层容器
  const appRef = ref()
  // * 定时函数
  const timer = ref(0)
  // * 默认缩放值
  const scale = {
    width: '1',
    height: '1',
  }

  // 设备的尺寸
  // const windowInnerWidth = 15360
  // const windowInnerHeight = 2160
  const windowInnerWidth = window.innerWidth
  const windowInnerHeight = window.innerHeight


  const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5))
  const calcRate = () => {

    // 当前宽高比
    const currentRate = parseFloat((windowInnerWidth / windowInnerHeight).toFixed(5))
    if (appRef.value) {
      if (currentRate >= baseProportion) {
        console.log(1)
        // 表示更宽
        scale.width = ((windowInnerHeight * baseProportion) / baseWidth).toFixed(5)
        scale.height = (windowInnerHeight / baseHeight).toFixed(5)
        appRef.value.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
      } else {
        console.log(2)
        // 表示更高
        scale.height = ((windowInnerWidth / baseProportion) / baseHeight).toFixed(5)
        scale.width = (windowInnerWidth / baseWidth).toFixed(5)
        appRef.value.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
      }
    }
  }

  const resize = () => {
    clearTimeout(timer.value)
    timer.value = setTimeout(() => {
      calcRate()
    }, 200)
  }

  // 改变窗口大小重新绘制
  const windowDraw = () => {
    window.addEventListener('resize', resize)
  }

  // 改变窗口大小重新绘制
  const unWindowDraw = () => {
    window.removeEventListener('resize', resize)
  }

  return {
    appRef,
    calcRate,
    windowDraw,
    unWindowDraw
  }
}
